<template>
  <view class="category-container">
    <!-- 新增按钮 -->
    <view class="action-bar">
      <button @click="showAddCategoryModal" class="action-button">新增分类</button>
    </view>

    <!-- 搜索框 -->
	<div style="color: red;font-size: 8px;">*注：1.0版本仅支持父类创建子类，暂不支持子类嵌套创建子类</div>
    <view class="search-bar">
      <input type="text" v-model="searchQuery" placeholder="搜索父分类" class="search-input" />
      <button @click="searchCategories" class="search-button">搜索</button>
    </view>
	

    <!-- 分类列表 -->
    <view class="category-list">
      <!-- 空空如也提示 -->
      <view v-if="filteredCategories.length === 0" style='display: flex;align-items: center;justify-content: center;margin-top: 50px;'>
        <image src='../../Resources/Image/空空如也.png' style='width: 120px;height:120px;'></image>
      </view>
      <view v-for="(category, index) in filteredCategories" :key="index">
		  <view v-if="category.pid === 0" class="category-item">
			  <view class="category-item2">
				  <view class="category-name">{{ category.category_name }}</view>
				  <view class="category-actions">
				    <image src='../../Resources/Image/添加子类.png' style='width: 25px;height:25px;margin-right: 5px;' @click="showAddSubCategoryModal(category)"></image>
				    <image src='../../Resources/Image/子类.png' style='width: 23px;height:20px;margin-right: 5px;' @click="toggleSubCategories(category)"></image>
				    <image src='../../Resources/Image/删除.png'  style='width: 27px;height:27px;' @click="deleteCategory(category)"></image>
				  </view>
			  </view>
			<br>
			
			<view style="font-size: 12px;font-weight: bold; color: #acacac;" v-if="Object.keys(category.showSubCategories).length === 0">&nbsp;当前没有子类，请点击父类加号添加</view>
			
			<view class="sub-category-list" v-if="Object.keys(category.showSubCategories).length != 0">
			  <view v-if="getSubCategories(category)" v-for="subCategory in category.showSubCategories" class="sub-category-item">
				<view class="sub-category-name">{{ subCategory.category_name }}</view>
				<view class="sub-category-actions">
				  <image src='../../Resources/Image/删除.png'  style='width: 27px;height:27px;' @click="deleteCategory(subCategory)"></image>
				</view>
			  </view>
			</view>
		</view>
      </view>
    </view>

    <!-- 新建分类弹窗 -->
    <view v-if="showModal" class="modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">新建分类</text>
        </view>
        <view class="modal-body">
          <input type="text" v-model="newCategory.name" placeholder="分类名称" class="input-field" />
          <input type="number" v-model="newCategory.weight" placeholder="排序权重" class="input-field" />
        </view>
        <view class="modal-footer">
          <button @click="submitCategory" class="action-button">提交</button>
          <button @click="hideModal" class="action-button">取消</button>
        </view>
      </view>
    </view>

    <!-- 新建子类弹窗 -->
    <view v-if="showSubCategoryModal" class="modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">新建子类</text>
        </view>
        <view class="modal-body">
          <view class="parent-category"><span style='font-size: 15px; font-weight: bold;'>父分类：</span>{{ parentCategory.name }}</view>
		  <div>&nbsp;</div>
          <input type="text" v-model="newSubCategory.name" placeholder="分类名称" class="input-field" />
          <input type="number" v-model="newSubCategory.weight" placeholder="排序权重" class="input-field" />
        </view>
        <view class="modal-footer">
          <button @click="submitSubCategory" class="action-button">提交</button>
          <button @click="hideSubCategoryModal" class="action-button">取消</button>
        </view>
      </view>
    </view>
	
  </view>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue';
import { config } from '../../config';
import { TokenStore } from '../../Store/TokenStore';
import { LoginState } from '../../util/LoginSate';
import { onPullDownRefresh , onReachBottom } from "@dcloudio/uni-app";

//展开子类的数组对象，使用id进行控制
//id:true
let ShowZL = ref([])

onMounted(()=>{
	if(!LoginState()){
		uni.showToast({
		  title: '登录失效',
		  icon: 'error'
		});
		uni.redirectTo({
			url:"/pages/index/index"
		})
		return ;
	}
	GetAllCategory();
})

onPullDownRefresh(()=>{
	GetAllCategory()
	uni.stopPullDownRefresh()
})

// 分类数据
const categories = ref([
	
]);

// 新建分类弹窗状态
const showModal = ref(false);
const newCategory = ref({ name: '', weight: null, pid: null });

// 新建子类弹窗状态
const showSubCategoryModal = ref(false);
const newSubCategory = ref({ name: '', weight: null, pid: null });
const parentCategory = ref({name:'',id:''});

// 搜索框数据
const searchQuery = ref('');


//从后端获取全部数据
function GetAllCategory(){
	uni.request({
		url:`${config.baseURL}/Goods/AllCategory`,
		method:'GET',
		header: {
			'content-type': 'application/json' // 设置请求头为 JSON
		},
		success:(res)=>{
			console.log(res.data.data);
			let data = JSON.parse(res.data.data);
			//console.log("数组结构化完成"+JSON.stringify(data))
			categories.value = data;
			for (let i = 0; i < categories.value.length; i++) {
			    let d = categories.value[i];
			    console.log("当前" + d.id);
			    ShowZL.value.push({ id: d.id, show: false });
			}
			console.log("全部状态："+JSON.stringify(ShowZL.value));
			
		},
		fail:(err)=>{
			uni.showToast({
			  title: err.errMsg,
			  icon: 'error'
			});
		}
	})
}

// 显示新建分类弹窗
const showAddCategoryModal = () => {
  showModal.value = true;
};

// 隐藏新建分类弹窗
const hideModal = () => {
  showModal.value = false;
};

// 提交新建分类
const submitCategory = () => {
	console.log(newCategory.value.name+newCategory.value.weight);
  if(newCategory.value.name === '' || newCategory.value.weight === null){
  	  uni.showToast({
  	    title: '请填写所有字段',
  	    icon: 'error'
  	  });
  	  return ;
  }
  else {
  	  let newPCategory = {name:newCategory.value.name,weight:newCategory.value.weight};
  	  uni.request({
  	  	url:`${config.baseURL}/Goods/AddPCategory`,
  		method:'POST',
  		data:newPCategory,
  		header: {
  			'content-type': 'application/json', // 设置请求头为 JSON
  			'Authorization': TokenStore().token
  		},
  		success:(res)=>{
  			console.log(res.data.data);
  			if(res.data.data === '0'){
  				uni.showToast({
  				  title: '系统繁忙',
  				  icon: 'error'
  				});
  			}
  			else if(res.data.data === '1'){
  				uni.showToast({
  				  title: '添加成功',
  				  icon: 'success'
  				});
				newCategory.value.name = '';
				newCategory.value.weight = null;
  				GetAllCategory()
  				hideModal();
  			}

			else if(res.data.data === 'error'){
				uni.showToast({
				  title: '数据库错误',
				  icon: 'error'
				});
			}
			else {
				uni.showToast({
				  title: '请重新登录',
				  icon: 'error'
				});
			}
  		},
  		fail:(err)=>{
  			uni.showToast({
  			  title: err.errMsg,
  			  icon: 'error'
  			});
  		}
  	  })
  }
};

// 编辑分类
const editCategory = (category) => {
  // 这里可以弹出编辑框，或者跳转到编辑页面
  //单独弹窗
  console.log('编辑分类', category);
};

// 删除分类
const deleteCategory = (category) => {
  newCategory.value.name = category.id;
  console.log("删除的id"+newCategory.value.name);
  uni.request({
  	url:`${config.baseURL}/Goods/DeleteCategory`,
	method:'POST',
	data:newCategory.value,
	header: {
		'content-type': 'application/json', // 设置请求头为 JSON
		'Authorization': TokenStore().token
	},
	success:(res)=>{
		console.log(res.data.data);
		if(res.data.data === '1'){
			uni.showToast({
			  title: "删除成功",
			  icon: 'success'
			});
			newCategory.value.name = '';
			GetAllCategory();
		}
		else if(res.data.data === 'error'){
			uni.showToast({
			  title: "数据库错误",
			  icon: 'error'
			});
		}
	},
	fail:(res)=>{
		uni.showToast({
		  title: res.errMsg,
		  icon: 'error'
		});
	}
  })
};

// 搜索分类
const filteredCategories = computed(() => {
  if (!searchQuery.value) {
    return categories.value;
  }
  return categories.value.filter(category =>
    category.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

const searchCategories = () => {
  // 搜索逻辑已经在 computed 中处理，这里可以留空或者添加其他逻辑
  uni.showToast({
    title: "测试版暂不支持查找分类",
    icon: 'none'
  });
};

// 显示新建子类弹窗
const showAddSubCategoryModal = (category) => {
	console.log(category.category_name);
  parentCategory.value.name = category.category_name;
  parentCategory.value.id = category.id;
  showSubCategoryModal.value = true;
};

// 隐藏新建子类弹窗
const hideSubCategoryModal = () => {
  showSubCategoryModal.value = false;
};

// 提交新建子类
const submitSubCategory = () => {
  if(newSubCategory.value.name === '' || newSubCategory.value.weight === null){
	  uni.showToast({
	    title: '请填写所有字段',
	    icon: 'error'
	  });
	  return ;
  }
  else {
	  newSubCategory.value.pid = parentCategory.value.id;
	  console.log("提交数据"+JSON.stringify(newSubCategory.value));
	  uni.request({
	  	url:`${config.baseURL}/Goods/AddSubCategory`,
		method:'POST',
		data:newSubCategory.value,
		header: {
			'content-type': 'application/json', // 设置请求头为 JSON
			'Authorization': TokenStore().token
		},
		success:(res)=>{
			console.log(res.data.data);
			if(res.data.data === '0'){
				uni.showToast({
				  title: '系统繁忙',
				  icon: 'error'
				});
			}
			else if(res.data.data === '1'){
				uni.showToast({
				  title: '添加成功',
				  icon: 'success'
				});
				newSubCategory.value.name = '';
				newSubCategory.value.pid = null;
				newSubCategory.value.weight = null;
				GetAllCategory()
				hideSubCategoryModal()
			}
			else if(res.data.data === 'error'){
				uni.showToast({
				  title: '数据库错误',
				  icon: 'error'
				});
			}
			else if(res.data.data === '令牌过期'){
				uni.showToast({
				  title: '请重新登录',
				  icon: 'error'
				});
			}
		},
		fail:(error)=>{
			uni.showToast({
			  title: error.errMsg,
			  icon: 'error'
			});
		}
	  })
  }
};

// 获取弹窗状态
const getSubCategories = (category) => {
  for(let i=0;i<ShowZL.value.length;i++){
	  if(ShowZL.value[i].id === category.id){
		  return ShowZL.value[i].show
	  }
  }
};



// 展开子类
const toggleSubCategories = (category) => {
  for(let i=0;i<ShowZL.value.length;i++){
	  if(ShowZL.value[i].id === category.id){
		  if(ShowZL.value[i].show === true){
			  ShowZL.value[i].show = false;
		  }
		  else {
			  ShowZL.value[i].show = true;
		  }
		  break;
	  }
  }
};
</script>

<style scoped>
.category-container {
  padding: 20px;
  background-color: #f7f7f7;
  height: 100vh;
}

.category-item2 {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}



.action-bar {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.action-button {
  border: none;
  border-radius: 5px;
  cursor: pointer;
  width: 80%;
  height: 40px;
  background-color: #4CAF50; /* Green */
  color: white;
  transition: background-color 0.3s;
}

.action-button:hover {
  background-color: #45a049;
}

.search-bar {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.search-input {
  padding: 10px;
  width:70%;
  border: 1px solid #eaeaea;
  border-radius: 5px;
  margin-right: 10px;
}

.search-button {
  border: none;
  border-radius: 5px;
  width:20%;
  cursor: pointer;
  height: 40px;
  background-color: #007aff; /* Blue */
  color: white;
  transition: background-color 0.3s;
}

.search-button:hover {
  background-color: #0051b3;
}

.category-list {
  width: 100%;
  margin: 0 auto;
}

.category-item {
  display: block; /* 或者使用 display: inline-block; */
  margin-bottom: 10px;
  padding: 10px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  margin-bottom: 10px; /* 根据需要调整间距 */
}

.category-item:hover {
transform: translateY(-5px);
}

.category-name {
flex-grow: 1;
color: #333;
}

.category-actions {
display: flex;
align-items: center;
}

.modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}

.modal-content {
background-color: #fff;
padding: 20px;
border-radius: 8px;
width: 90%;
max-width: 400px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.modal-header {
font-size: 18px;
font-weight: bold;
color: #007aff;
border-bottom: 1px solid #eaeaea;
padding-bottom: 10px;
margin-bottom: 20px;
}

.modal-body {
margin: 20px 0;
}

.input-field {
width: 90%;
padding: 10px;
margin-bottom: 20px;
border: 1px solid #eaeaea;
border-radius: 5px;
}

.modal-footer {
display: flex;
justify-content: flex-end;
}

.modal-footer button {
margin-left: 10px;
}

.empty-message {
text-align: center;
font-size: 24px;
color: #888;
margin-top: 50px;
}

.sub-category-list {
margin-left: 20px;
border-left: 2px solid #eaeaea;
padding-left: 10px;
}

.sub-category-item {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
padding: 5px;
background-color: #f7f7f7;
border-radius: 8px;
}

.sub-category-name {
flex-grow: 1;
color: #333;
}

.sub-category-actions {
display: flex;
align-items: center;
}
</style>